<?php

/**
 * 同时利用MemcacheQ和MemcacheDB的队列
 */
class PHPDuilie {
    public function __construct($sName) {
        $this->oMemcacheQ = new Memcache();
        $this->oMemcacheDB = new Memcache();
        $this->sName = $sName;
    }

    protected $oMemcacheQ;
    protected $oMemcacheDB;
    protected $sName;

    public function addQServer($sHost, $iPort) {
        $this->oMemcacheQ->addServer($sHost, $iPort);
    }
    public function addQServers($aServers) {
        if($aServers) foreach($aServers as $s) {
            $this->addQServer($s['host'], $s['port']);
        }
    }
    public function addDBServer($sHost, $iPort) {
        $this->oMemcacheDB->addServer($sHost, $iPort);
    }
    public function addDBServers($aServers) {
        if($aServers) foreach($aServers as $s) {
            $this->addDBServer($s['host'], $s['port']);
        }
    }

    public function enqueue($mValue) {
        $iMaxRetryTimes = 10;
        $i = 0;
        do {
            $sKey = "queue_item_" . $this->sName . "_" . microtime();
            $i++;
        } while($i <= $iMaxRetryTimes && !$this->oMemcacheDB->add($sKey, json_encode($mValue)));

        if($i > $iMaxRetryTimes) {
            throw new Exception("Cannot enqueue");
        }

        $this->oMemcacheQ->set($this->sName, $sKey);
    }

    public function dequeue() {
        $sKey = $this->oMemcacheQ->get($this->sName);
        if(!$sKey) {
            return null;
        }

        $sJSON = $this->oMemcacheDB->get($sKey);
        if(!$sJSON) {
            return null;
        }

        $mRetval = json_decode($sJSON, true);
        $this->oMemcacheDB->delete($sKey);

        return $mRetval;
    }
}

?>